package com.sirui.x.io.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.sirui.x.global.ServiceException;

public class ServerSocketWrapper {

	public static final int LISTEN_PORT = 4000;
	private static final int CORE_SIZE = 50;
	private static final int MAX_SIZE = 200;
	
	private ThreadPoolExecutor pool = new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, 60, TimeUnit.SECONDS, new SynchronousQueue<>());
	
	public void startAndListen() throws IOException {
		try(ServerSocket ss = new ServerSocket(LISTEN_PORT)){
			while(true) {
				handleAsync(ss.accept());
			}
		}
		
	}

	private void handleAsync(Socket accept) {
		int random = new Random().nextInt(1);
		SocketRunnable task = new SocketRunnable(accept);
		// 新起线程处理，可以使用线程池
		switch (random) {
		case 0:
			new Thread(task).start();
			break;
		case 1:
			pool.execute(task);
			break;

		default:
			throw new ServiceException("unreachable.");
		}
	}
}
